﻿using System.Collections.ObjectModel;
using System.Windows;
using Windows.Networking.Proximity;
using Microsoft.Phone.Controls;

namespace NFC_Test
{
    public partial class MainPage : PhoneApplicationPage
    {
        /// <summary>
        /// 消息类型
        /// </summary>
        private const string MESSAGE_TYPE = "Windows.MFCTest";
        /// <summary>
        /// 消息记录
        /// </summary>
        private readonly ObservableCollection<string> chartData = new ObservableCollection<string>();
        // 构造函数

        private ProximityDevice device;
        /// <summary>
        /// 是否连接
        /// </summary>
        private bool isConnected;

        /// <summary>
        /// 注册接收消息ID
        /// </summary>
        private long subscribeForMessageID;

        public MainPage()
        {
            InitializeComponent();

            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();


            if (!checkSupportNFC())
            {
                MessageBox.Show("Your Phon not support NFC!");
                return;
            }
            device.DeviceArrived += device_DeviceArrived;
            device.DeviceDeparted += device_DeviceDeparted;

            btnSend.IsEnabled = txtSend.IsEnabled = false;
            lstLog.ItemsSource = chartData;
        }

        /// <summary>
        /// 检查并获取NFC设备
        /// </summary>
        /// <returns></returns>
        private bool checkSupportNFC()
        {
            if (device == null)
                device = ProximityDevice.GetDefault();
            return device != null;
        }

        /// <summary>
        /// NFC断开
        /// </summary>
        /// <param name="sender"></param>
        private void device_DeviceDeparted(ProximityDevice sender)
        {
            isConnected = false;
            if (subscribeForMessageID != -1)
            {
                sender.StopSubscribingForMessage(subscribeForMessageID);
                subscribeForMessageID = -1;
            }
            Dispatcher.BeginInvoke(() =>
            {
                //MessageBox.Show("Deivce Departed!");
                btnSend.IsEnabled = false;
                txtSend.IsEnabled = false;
            });
        }

        /// <summary>
        /// NFC连接
        /// </summary>
        /// <param name="sender"></param>
        private void device_DeviceArrived(ProximityDevice sender)
        {
            isConnected = true;
            //注册接收消息
            subscribeForMessageID=device.SubscribeForMessage(MESSAGE_TYPE, messageReceived);
            Dispatcher.BeginInvoke(() =>
            {
                //MessageBox.Show("Connected device:" + sender.DeviceId);
                btnSend.IsEnabled = true;
                txtSend.IsEnabled = true;
            });
        }

        /// <summary>
        /// 接收到消息
        /// </summary>
        /// <param name="device"></param>
        /// <param name="message"></param>
        private void messageReceived(ProximityDevice device, ProximityMessage message)
        {
            Dispatcher.BeginInvoke(() =>
            {
                chartData.Insert(0, string.Format("{0}:{1}", device.DeviceId,
                    message.DataAsString));
            });
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (!isConnected)
                return;
            string content = txtSend.Text.Trim();
            if (string.IsNullOrEmpty(content))
                return;
            device.PublishMessage(MESSAGE_TYPE, content);
            txtSend.Text = "";
        }

        // 用于生成本地化 ApplicationBar 的示例代码
        //private void BuildLocalizedApplicationBar()
        //{
        //    // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
        //    ApplicationBar = new ApplicationBar();

        //    // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // 使用 AppResources 中的本地化字符串创建新菜单项。
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }
}